package cn.itcast.ecshop.db;

import android.content.Context;

import java.sql.SQLException;
import java.util.List;
import java.util.Set;

import cn.itcast.ecshop.bean.CartItem;

/**
 * Created by Administrator on 2016/8/4.
 */
public class ShopCartManager {

    private static Context mContext;

    public static void init(Context context) {

        mContext = context;
    }

    public static void addOrUpdateToCart(int productId, int productNum, Set<Integer> productProperties) throws SQLException {

        if (productNum == 0) {

            productNum = 1;
        }
        List<CartItem> list = MyOrmLiteSqliteOpenHelper.getInstance(mContext).getShopCartDao()
                .queryBuilder().where().eq("productId", productId).query();
        if (list != null && list.size() > 0) {

            CartItem item = list.get(0);
            item.setProductNum(productNum);
            item.setProductProperties(productProperties);
            MyOrmLiteSqliteOpenHelper.getInstance(mContext).getShopCartDao().update(item);

           /* CartItem cartItem = new CartItem(productId, productNum, productProperties);
            //MyOrmLiteSqliteOpenHelper.getInstance(mContext).getShopCartDao().update(cartItem);
            MyOrmLiteSqliteOpenHelper.getInstance(mContext).getShopCartDao()
                    .updateRaw("update " + CartItem.SHOP_CART_TABLE_NAME + "set productNum=? productPropertiesStr=? WHERE productId = ?",
                            cartItem.getProductNum() + "", cartItem.getProductProperties() + "", cartItem.getProductId() + "");*/
        } else {

            MyOrmLiteSqliteOpenHelper.getInstance(mContext).getShopCartDao().create(new CartItem(productId, productNum, productProperties));
        }
    }

    public static CartItem getCartItemByProductId(String productId) throws SQLException {

        return (CartItem) MyOrmLiteSqliteOpenHelper.getInstance(mContext).getShopCartDao().queryForId(productId);
    }

    public static void deleteCartItem(String productId) throws SQLException {

        MyOrmLiteSqliteOpenHelper.getInstance(mContext).getShopCartDao().deleteById(productId);
    }

    public static String getShopCartStr() throws SQLException {

        List<CartItem> cartItems = MyOrmLiteSqliteOpenHelper.getInstance(mContext).getShopCartDao().queryForAll();
        if (cartItems == null || cartItems.size() < 1) {

            return "";
        }

        StringBuilder stringBuilder = new StringBuilder();
        for (CartItem cartItem : cartItems) {

            stringBuilder.append(cartItem.toString()).append("|");
        }

        stringBuilder.deleteCharAt(stringBuilder.length() - 1);

        return stringBuilder.toString();
    }

    public static void clearShopCart() throws SQLException {

        MyOrmLiteSqliteOpenHelper.getInstance(mContext).getShopCartDao().queryRaw("delete from " + CartItem.SHOP_CART_TABLE_NAME);
    }

}
